package myzzyl.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import myzzyl.constants.ErrorConstants;
import myzzyl.exception.BusinessException;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;


/**
 * 设置资源拦截器
 */
@Slf4j
@Component
public class ResourceInterceptor implements HandlerInterceptor {

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是处理器方法（如静态资源），直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        log.info("设置资源拦截器, url: {}", request.getRequestURI());
        // 构造资源访问路径 请求方式+路径
        String targetRequest = request.getMethod() + request.getRequestURI();
        log.info("构造资源访问路径, {}", targetRequest);

        // 取出当前账号绑定的所有资源
        List<String> permissionList = StpUtil.getPermissionList();
        // 遍历判断是否有匹配的
        for (String permission : permissionList) {
            if (antPathMatcher.match(permission, targetRequest)) {
                return true;
            }
        }

        // 没有匹配上的，抛出权限不足异常
        throw new BusinessException(ErrorConstants.FORBIDDEN);
    }
}

